<?php
namespace Admin\Controller;
require_once 'Qiniu/autoload.php';
use \Qiniu\Auth;
use \Qiniu\Storage\UploadManager;
use Think\Controller;

class FrontCategoryController extends Controller {

	/**
	 * 栏目管理
	 * @return [type] [description]
	 */
	public function index() {

		$map = array();

		$name = I('get.name');
		if($name) {
			$map['name'] = $name;
		}

        $model = M('FrontCategory');
        $total = $model->where($map)->count();
        $page = new \Think\Page($total, 25);
        $show = $page->show();

        $categoryList = $model->where($map)
        			 ->order('sort DESC')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        foreach($categoryList as $key => $val) {
        	$categoryList[$key]['category_type'] = M('FrontCategoryType')->where(array('id' => $val['category_type']))->getField('category_type');
        }             

		$this->assign('showpage', $show);
		$this->assign('categoryList', $categoryList);

		$this->display();
	}

	/**
	 * 添加栏目
	 */
	public function addCategory() {
		if(IS_POST) {
			$dataGet['name'] = I('post.name', '');
			$dataGet['status'] = I('post.status', 1); // 文稿标题
			$dataGet['is_category_show'] = I('post.is_category_show', 1); // 文稿作者
			$dataGet['is_category_more'] = I('post.is_category_more', ''); // 文稿内容
			$dataGet['category_type'] = I('post.category_type', 'recommend');
			//$dataGet['sort'] = I('post.sort', 0);
			$dataGet['create_time'] = time();
			$dataGet['update_time'] = time();

			/*if($_FILES['image_url']['size'] > 0) {
				$upload = new \Think\Upload();
			    $upload->maxSize   =     3145728 ;// 设置附件上传大小
			    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
			    $upload->rootPath  =     './Html/Uploads/fcategory/'; 
			    $upload->savePath  =     ''; 
			    $info   =   $upload->upload();
			    if(!$info) {// 上传错误提示错误信息
			        $this->error($upload->getError());
			    }else{
			    	$dataGet['image_url'] = 'fcategory/'. $info['image_url']['savepath'] . $info['image_url']['savename'];
			    }

			}*/

			$rules = array(
			    array('name','require','栏目名称必须填写'), 
			);

			$model = M('FrontCategory');
			if (!$model->validate($rules)->create($dataGet)){
			    $this->error($model->getError());
			}else{
			    $res = $model->add($dataGet);
                $model->where(array('id' => $res))->save(array('sort' => $res));
			    if($res) {
			    	$this->success('添加成功');
			    } else {
			    	$this->error('添加失败');
			    }
			}

		}
	}

	/**
	 * 修改栏目
	 * @return [type] [description]
	 */
	public function editCategory() {
		if(IS_POST) {
			$dataGet['id'] = I('post.id', '');
			$dataGet['name'] = I('post.name', '');
			$dataGet['status'] = I('post.status', 1); // 文稿标题
			$dataGet['is_category_show'] = I('post.is_category_show', 1); // 文稿作者
			$dataGet['is_category_more'] = I('post.is_category_more', ''); // 文稿内容
			$dataGet['category_type'] = I('post.category_type', 'recommend');
			$dataGet['sort'] = I('post.sort', 0);
			$dataGet['update_time'] = time();

			if($_FILES['image_url']['size'] > 0) {
				$upload = new \Think\Upload();
			    $upload->maxSize   =     3145728 ;// 设置附件上传大小
			    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
			    $upload->rootPath  =     './Html/Uploads/fcategory/'; 
			    $upload->savePath  =     ''; 
			    $info   =   $upload->upload();
			    if(!$info) {// 上传错误提示错误信息
			        $this->error($upload->getError());
			    }else{
			    	$dataGet['image_url'] = 'fcategory/'. $info['image_url']['savepath'] . $info['image_url']['savename'];
			    }

			}

			$rules = array(
			    array('name','require','栏目名称必须填写'), 
			);

			$model = M('FrontCategory');
			if (!$model->validate($rules)->create($dataGet)){
			    $this->error($model->getError());
			}else{
				// print_r($dataGet);exit;
			    $res = $model->save($dataGet);
			    if($res !== false) {
			    	$this->success('修改成功');
			    } else {
			    	$this->error('修改失败');
			    }
			}

		}
	}

	/**
	 * ajax获取栏目
	 * @param  integer $id [description]
	 * @return [type]      [description]
	 */
    public function ajaxGetCategoryInfo($id=0){
        $model = M('FrontCategory');
        if($id){
            $info = $model->where('id=' . $id)->find();
            if($info){
                $this->ajaxReturn($info);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }
    }


	/**
	 * 删除后台用户
	 * @return [type] [description]
	 */
	public function ajaxDelCategory() {
		if(IS_GET) {
			$id = I('get.id');
		} elseif(IS_POST) {
			$id = I('post.id');
			is_array($id) && $id = implode(',', $id);
		}

		if(empty($id)) {
			$message['status'] = -1;
			$message['msg'] = '选项不能为空';
			$this->ajaxReturn($message);
		}

		$map['id'] = array('in', $id);
		$res = M('FrontCategory')->where($map)->delete();
		if($res) {
			$message['status'] = 1;
			$message['msg'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['status'] = -1;
			$message['msg'] = '删除失败，请重试';
			$this->ajaxReturn($message);
		}
	}

	/**
	 * 栏目类型管理
	 * @return [type] [description]
	 */
	// public function typeIndex() {
	// 	$map = array();

	// 	$name = I('get.name');
	// 	if($name) {
	// 		$map['name'] = $name;
	// 	}

 //        $model = M('FrontCategory');
 //        $total = $model->where($map)->count();
 //        $page = new \Think\Page($total, 25);
 //        $show = $page->show();

 //        $categoryList = $model->where($map)
 //        			 ->order('sort asc')
 //                     ->limit($page->firstRow .',' . $page->listRows)
 //                     ->select();

	// 	$this->assign('showpage', $show);
	// 	$this->assign('categoryList', $categoryList);

	// 	$this->display();
	// }
	
	public function getLiveList() {
		$cid = I('get.cid');
		$model = M('Live');
		$map = array('v_status'=>1);
		if(I('get.title')){
			$map['title']=array('like',"%".I('get.title')."%");
		}

        $list = $model->where($map)->group('group_id')->select();
        $total = count($list);
        $page = new \Think\Page($total, 20);
        $show = $page->show();

        $liveList = $model->where($map)
        			 ->order('sort Desc, create_time desc')
        			 ->group('group_id')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();
        foreach($liveList as $key => $val) {
        	$tmp = M('Publish')->where(array('category_id' => $cid, 'live_group_id' => $val['group_id']))->find();
        	if($tmp) {
        		$liveList[$key]['is_add'] = 1;
        	} else {
        		$liveList[$key]['is_add'] = 0;
        	}
        }


		$this->assign('showpage', $show);
		$this->assign('liveList', $liveList);

		$this->display();
	}

	public function addCategoryLive() {
		if(IS_GET) {
			$group_id = I('get.group_id');
		} elseif (IS_POST) {
			$group_id = I('post.group_id');
		}


		$cid = I('get.cid');
		//$group_id = I('get.group_id');
		$c_type = I('get.c_type');
		if($cid) {
			if($group_id) {



				// $live_info = M('Live')
				// 			->where(array('group_id' => $group_id))
				// 			->group('group_id')->find();

				$dataGet['category_id'] = $cid;
				$dataGet['live_group_id'] = $group_id;
				$dataGet['type'] = 'live';
				$l=M('Publish')->where($dataGet)->find();
				if($l){
						$this->error('已经添加');
				}else{
					$dataGet['update_time'] = time();

					$res = M('Publish')->add($dataGet);
					if($res) {
						M('Publish')->where(array('id' => $res))->save(array('sort' => $res));
						$this->success('添加成功');
					} else {
						$this->error('添加失败');
					}
				}				

			} else {
				$this->error('直播ID不存在');
			}

		} else {
			$this->error('栏目ID不存在');
		}
	}

	public function getSpecialList() {
		$cid = I('get.cid');
		$model = M('FrontTheme');
		$map = array();
        $list = $model->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 20);
        $show = $page->show();

        $specialList = $model->where($map)
        			 ->order('sort desc')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

        foreach($specialList as $key => $val) {
        	$tmp = M('Publish')->where(array('category_id' => $cid, 'theme_id' => $val['id']))->find();
        	if($tmp) {
        		$specialList[$key]['is_add'] = 1;
        	} else {
        		$specialList[$key]['is_add'] = 0;
        	}
        }


		$this->assign('showpage', $show);
		$this->assign('specialList', $specialList);

		$this->display();
	}

    public function getAuthorList() {
        $cid = I('get.cid');
        $nickname=I('get.name');
        $model = M('FrontUser');
        $map = array();
        $map['reporter_id']=array('neq',0);
        if($nickname){
            $map['nickname']=$nickname;
        }
        $list = $model->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 20);
        $show = $page->show();

        $authorList = $model->where($map)
            ->limit($page->firstRow .',' . $page->listRows)
            ->select();

        foreach($authorList as $key => $val) {
            $tmp = M('Publish')->where(array('category_id' => $cid, 'user_id' => $val['front_user_id']))->find();
            if($tmp) {
                $authorList[$key]['is_add'] = 1;
            } else {
                $authorList[$key]['is_add'] = 0;
            }
        }


        $this->assign('showpage', $show);
        $this->assign('authorList', $authorList);

        $this->display();
    }

	public function addSpecialLive() {
		$cid = I('get.cid');
		$sid = I('get.sid');
		if($cid) {
			if($cid) {
				// $spec_info = model('FrontTheme')->where(['id' => $sid])->find();

				$dataGet['category_id'] = $cid;
				$dataGet['theme_id'] = $sid;
				$dataGet['type'] = 'special';
				$dataGet['update_time'] = time();

				$res = M('Publish')->add($dataGet);
				if($res) {
					M('Publish')->where(array('id' => $res))->save(array('sort' => $res));
					$this->success('添加成功');
				} else {
					$this->error('添加失败');
				}

			} else {
				$this->error('直播ID不存在');
			}

		} else {
			$this->error('栏目ID不存在');
		}
	}

    public function addAuthorLive() {
        $cid = I('get.cid');
        $sid = I('get.sid');
        if($cid) {
            if($cid) {
                // $spec_info = model('FrontTheme')->where(['id' => $sid])->find();

                $dataGet['category_id'] = $cid;
                $dataGet['user_id'] = $sid;
                $dataGet['type'] = 'author';
                $dataGet['update_time'] = time();

                $res = M('Publish')->add($dataGet);
                if($res) {
                    M('Publish')->where(array('id' => $res))->save(array('sort' => $res));
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }

            } else {
                $this->error('直播ID不存在');
            }

        } else {
            $this->error('栏目ID不存在');
        }
    }

	/**
	 * 管理内容
	 * @return [type] [description]
	 */
	public function manageCategoryContent() {
        $cid=I('get.cid');
        $ctype=I('get.ctype');
        $name=I('get.name');
        $putPolicy=array(
            'saveKey'=>'sliderList/$(etag)',
        );
        $upAuth = new Auth(C('QINIU_accessKey'), C('QINIU_secretKey'));
        // $bucket = 'images';
        $bucket = C('QINIU_BUCKET');
        $uploadToken = $upAuth->uploadToken($bucket,null, 3600,$putPolicy);

        $map['category_id']=$cid;

        if($name){
        	switch($ctype){
                    case 'live':
                        $r=M('Live')->where(array('title'=>array('like',"%".$name."%")))->getField('group_id',true);
                        $map['live_group_id']=array('in',$r);
                        break;
                    case 'special':
                    	$r=M('FrontTheme')->where(array('name'=>array('like',"%".$name."%")))->getField('id',true);
                    	$map['theme_id']=array('in',$r);
                        break;
                    case 'author':
                        $r=M('UserInfo')->where(array('realname'=>array('like',"%".$name."%")))->getField('uid',true);
                        $map['user_id']=array('in',$r);
                        break;
                }
        	$map['category_id']=$cid;
        }
        
        $this->assign('uploadToken', $uploadToken);
		$count=M('Publish')->order('sort DESC')->where($map)->count();
        $page = new \Think\Page($count, 80);
        $show = $page->show();

        $contentList=M('Publish')->order('sort DESC')->where($map)->limit($page->firstRow .',' . $page->listRows)->select();
        if($ctype!='slider'){
            foreach($contentList as $k=>$v){
                switch($v['type']){
                    case 'live':
                        $r=M('Live')->where(array('group_id'=>$v['live_group_id']))->find();
                        $contentList[$k]['title']=$r['title'];
                        $contentList[$k]['image_url']=$r['image_url'];
                        break;
                    case 'special':
                        $r=M('FrontTheme')->find($v['theme_id']);
                        $contentList[$k]['title']=$r['name'];
                        $contentList[$k]['image_url']=$r['image_url'];
                        break;
                    case 'author':
                        $r=M('FrontUser')->find($v['user_id']);
                        $contentList[$k]['title']=$r['nickname'];
                        $contentList[$k]['image_url']=$r['avatar'];
                        break;
                }
            }
        }else{
            foreach($contentList as $k=>$v){
                switch($v['type']){
                    case 'live':
                        $r=M('Live')->where(array('group_id'=>$v['live_group_id']))->find();
                        $contentList[$k]['title']=$r['title'];
                        break;
                    case 'special':
                        $r=M('FrontTheme')->find($v['theme_id']);
                        $contentList[$k]['title']=$r['name'];
                        break;
                    case 'author':
                        $r=M('FrontUser')->find($v['user_id']);
                        $contentList[$k]['title']=$r['nickname'];
                        break;
                }
            }
        }

        
        


        $this->assign('showpage', $show);
        $this->assign('contentList', $contentList);
		$this->display(); 
	}

	public function getLiveListWithPub() {
		$cid = I('get.cid');
		$pModel = M('Publish');
		$map['p.category_id'] = $cid;
		$map['p.type'] = 'live';

		$name = I('get.name');
		if($name) {
			$map['l.title'] = $name;
		}

        $list = $pModel->alias('p')->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 20);
        $show = $page->show();

        $pList = $pModel->alias('p')
        			 ->field('p.id pubid,p.sort psort,l.*')
        			 ->join('__LIVE__ AS l ON p.live_group_id = l.group_id')
        			 ->where($map)
        			 // ->order('p.sort asc')
        			 ->order('ABS(unix_timestamp(now()) - p.sort) ASC')
        			 ->group('l.group_id')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

		$this->assign('showpage', $show);
		$this->assign('pList', $pList);

		$this->display();	
	}

	public function getSpecialListWithPub() {
		$cid = I('get.cid');
		$pModel = M('Publish');
		$map['p.category_id'] = $cid;
		$map['p.type'] = 'special';

		$name = I('get.name');
		if($name) {
			$map['ft.name'] = $name;
		}

        $list = $pModel->alias('p')->where($map)->select();
        $total = count($list);
        $page = new \Think\Page($total, 20);
        $show = $page->show();

        $pList = $pModel->alias('p')
        			 ->field('p.id pubid,p.sort psort,ft.*')
        			 ->join('__FRONT_THEME__ AS ft ON p.theme_id = ft.id')
        			 ->where($map)
        			 ->order('p.sort asc')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

		$this->assign('showpage', $show);
		$this->assign('pList', $pList);

		$this->display();	
	}

	public function delCategoryContent() {
		$id = I('get.id');

		if(empty($id)) {
			$this->error('ID不能为空');
		}

		$map['id'] = $id;
		$res = M('Publish')->where($map)->delete();
		if($res) {
			$this->success('删除成功');			
		} else {
			$this->error('删除失败，请重试');
		}		
	}

	/**
	 * 上传轮播封面图
	 * @return [type] [description]
	 */
	public function uploadThumbForPub() {
		if(IS_POST) {
			$id = I('post.id');
			if($id) {
				if($_FILES['image_url']['size'] > 0) {
					$upload = new \Think\Upload();
				    $upload->maxSize   =     3145728 ;// 设置附件上传大小
				    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');
				    $upload->rootPath  =     './Html/Uploads/slider/'; 
				    $upload->savePath  =     ''; 
				    $info   =   $upload->upload();
				    if(!$info) {// 上传错误提示错误信息
				        $this->error($upload->getError());
				    }else{
				    	$dataGet['image_url'] = 'slider/'. $info['image_url']['savepath'] . $info['image_url']['savename'];

				    	$res = M('Publish')->where(array('id' => $id))->save($dataGet);
					    if($res !== false) {
					    	$this->success('添加成功');
					    } else {
					    	$this->error('添加失败');
					    }

				    }
				} else {
					$this->error('请选择要上传的图片');
				}

			} else {
				$this->error('未指定ID');
			}
		}		
	}

	public function ajaxGetSliderThumb($id = 0) {
        $model = M('Publish');
        if($id){
            $info = $model->where('id=' . $id)->find();
            if($info){
                $this->ajaxReturn($info);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }	
	}

	public function ajaxGetSort($id = 0) {
        $model = M('Publish');
        if($id){
            $info = $model->where('id=' . $id)->find();
            if($info){
                $this->ajaxReturn($info);
            }else{
                $this->ajaxReturn(0);
            }
        }else{  
            return false;
        }	
	}


	public function setResourceSort() {
		$id = I('post.id');
		$sort = I('post.sort');
        $model = M('Publish');
        if($id){
        	$dataGet['sort'] = $sort;
            $info = $model->where('id=' . $id)->save($dataGet);
            if($info){
                $this->success('更新成功');
            }else{
                $this->error('更新失败');
            }
        }else{  
           $this->error('未指定ID');
        }	
	}

	public function getAllList() {
		$cid = I('get.cid');
		if($cid) {
			$c_map['id'] = $cid;
			$c_model = M('FrontCategory');
			$c_info = $c_model->where($c_map)->find();

			if($c_info) {
				$p_model = M('Publish');
				$p_map['category_id'] = $cid;
				$total = $p_model->where($p_map)->count();
		        $page = new \Think\Page($total, 20);
		        $show = $page->show();

		        $list = $p_model->where($p_map)
        			 ->order('ABS(cast(unix_timestamp() as SIGNED)-cast(sort as SIGNED)) ASC, update_time DESC')
                     ->limit($page->firstRow .',' . $page->listRows)
                     ->select();

                $data = array();


      //   $pList = $pModel->alias('p')
      //   			 ->field('p.id pubid,p.sort psort,ft.*')
      //   			 ->join('__FRONT_THEME__ AS ft ON p.theme_id = ft.id')
      //   			 ->where($map)
      //   			 ->order('p.sort asc')
      //                ->limit($page->firstRow .',' . $page->listRows)
      //                ->select();

      //   $pList = $pModel->alias('p')
      //   			 ->field('p.id pubid,p.sort psort,l.*')
      //   			 ->join('__LIVE__ AS l ON p.live_group_id = l.group_id')
      //   			 ->where($map)
      //   			 // ->order('p.sort asc')
      //   			 ->order('ABS(unix_timestamp(now()) - p.sort) ASC')
      //   			 ->group('l.group_id')
      //                ->limit($page->firstRow .',' . $page->listRows)
      //                ->select();

      //           foreach($list as $key => $val) {
      //           	if($val['type'] == 'live') {
						// $p_model = M('Publish');
						// $map['p.id'] = $val['id'];

				  //       $pList = $p_model->alias('p')
				  //       			 ->field('p.id pubid,p.sort psort,l.*')
				  //       			 ->join('__LIVE__ AS l ON p.live_group_id = l.group_id')
				  //       			 ->where($map)
				  //       			 ->order('ABS(unix_timestamp(now()) - p.sort) ASC')
				  //       			 ->group('l.group_id')
				  //                    ->limit($page->firstRow .',' . $page->listRows)
				  //                    ->select();               		
      //           		$data[$key] = 
      //           	}
      //           }


				$this->assign('showpage', $show);
				$this->assign('list', $list);

				$this->display();	
			} else {
				$this->error('栏目不存在');
			}

		} else {
			$this->error('未指定ID');
		}
	}

	public function ajaxSetStatus(){
        $cid=I('get.cid');
        $state=I('get.state');
        $res=$this->setCategory($cid,'status',$state);
        $this->ajaxReturn($res);
    }
    public function ajaxSetShowTitle(){
        $cid=I('get.cid');
        $state=I('get.state');
        $res=$this->setCategory($cid,'is_category_show',$state);
        $this->ajaxReturn($res);
    }
    public function ajaxSetShowMore(){
        $cid=I('get.cid');
        $state=I('get.state');
        $res=$this->setCategory($cid,'is_category_more',$state);
        $this->ajaxReturn($res);
    }



    public function setCategory($cid,$field,$state){
        if($cid!="" && $state!="" && $field!=""){
            $res=M('FrontCategory')->save(array('id'=>$cid,$field=>$state));;
            if($res===false){
                $mess['resultCode']=1;
                $mess['info']='修改失败';
            }else{
                $mess['resultCode']=0;
                $mess['info']='修改成功';
            }
        }else{
            $mess['resultCode']=1;
            $mess['info']='参数错误';
        }

        return $mess;
    }


    public function ajaxSetSort(){
        $ids=I('get.sortedIDs');
        $sortNum=I('get.sortNum');
        M()->startTrans();
        foreach($ids as $k=>$v){
            $res=M('Publish')->save(array('id'=>$v,'sort'=>$sortNum[$k]));
            if($res===false){
                M()->rollback();
                $this->ajaxReturn(array('resultCode'=>1,'info'=>'排序修改失败！'));
            }
        }
        M()->commit();
        $this->ajaxReturn(array('resultCode'=>0,'info'=>'排序修改成功！'));
    }


    public function ajaxDelItem(){
        $id=I('get.id');
        if($id){
            $res=M('Publish')->delete($id);
            if($res===false){
                echo 0;
            }else{
                echo 1;
            }
        }else{
            echo 0;
        }
    }

    public function ajaxSetState(){
        $cid=I('get.cid');
        $state=I('get.state');
        if($cid!="" && $state!=""){
            $res=M('Publish')->save(array('id'=>$cid,'state'=>$state));;
            if($res===false){
                $mess['resultCode']=1;
                $mess['info']='修改失败';
            }else{
                $mess['resultCode']=0;
                $mess['info']='修改成功';
            }
        }else{
            $mess['resultCode']=1;
            $mess['info']='参数错误';
        }

        $this->ajaxReturn($mess);
    }

    public function ajaxGetItemInfo($id=0){
        $model = M('Publish');
        if($id){
            $info = $model->find($id);
            if($info){
                $this->ajaxReturn($info);
            }else{
                $this->ajaxReturn(0);
            }
        }else{
            return false;
        }

    }


    public function editItem(){
        unset($_POST['file']);
        $model = M('Publish');

        $info = $model->save(I('post.'));
        if($info===false){
            $this->error('修改失败！');
        }else{
            $this->success('修改成功！');
        }
    }
} 